#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

void error(const char *msg)
{
	perror(msg);
	exit(1);
}

void strrev(char *s)
{
	int len = strlen(s);
	for (int i=0, j=len-1; i<j; ++i, --j)
	{
		char tmp = s[i];
		s[i] = s[j];
		s[j] = tmp;

	}
}

int main(int argc, char *argv[])
{
	// opening socket
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) error("error opening socket");
	
	// binding
	sockaddr_in bind_addr;
	memset(&bind_addr, 0, sizeof(bind_addr));
	bind_addr.sin_family = AF_INET;
	bind_addr.sin_addr.s_addr = INADDR_ANY;
	// bind_addr.sin_port = htons(server_options.port_number);
	bind_addr.sin_port = 46572;
	if (bind(sockfd, (sockaddr*)&bind_addr, sizeof(bind_addr)) < 0)
		error("error binding");
		
	// listening to connections
	listen(sockfd, 5);
	
	// waits forever for a client connection
	while (true)
	{
		sockaddr_in client_addr;
		int addrlen = sizeof(client_addr);
		int connfd = accept(sockfd, (sockaddr*)&client_addr, (socklen_t*)&addrlen);
		char buf[1<<10];
		read(connfd, buf, 1<<10);
		printf("Received: %s, ", buf);
		strrev(buf);
		printf("sending: %s\n", buf);
		write(connfd, buf, strlen(buf)+1);
	}
}
